<template>
    <div>
      <!-- 滚动内容 start -->
      <el-scrollbar class="app-container-scroll-bar">
        <pageTitle :title="pageTitle" :hasBack="true"></pageTitle>

        <!-- 规则 start-->
        <div class="wrap">
        <span style="margin-left: 25px;font-size:16px;color: rgb(96, 98, 102);">关联资源</span>
        <el-form ref="addForm"  :rules="rules" :model="addForm" label-width="120px"> 
          <el-form-item label="资源类型" prop="monitorType" style="margin:20px 0;">
            <el-select size="small" v-model="addForm.monitorType" @change="handleChooseType(addForm.monitorType)">
              <el-option label="主机" value="0"></el-option>
              <el-option label="容器" value="1"></el-option>
            </el-select>
          </el-form-item>
          
          <span style="margin-left: 25px;font-size:16px;color: rgb(96, 98, 102);">设置规则</span>
          <el-form-item label="规则名称" prop="name" style="margin:20px 0;">
            <el-input style="width:200px" size="small" v-model="addForm.name"></el-input>
          </el-form-item>

          <el-form-item label="添加规则">
            <table  class="dialog-table">
                <tr>
                  <th>规则描述</th>
                  <th>参照类型</th>
                  <th>运算符</th>
                  <th style="width:80px">阀值</th>
                  <th>单位</th>
                  <th style="width:120px">监控频率/分钟</th>
                  <th>监控指标</th>
                  <th>出现次数</th>
                  <th style="width:130px">操作</th>
                 </tr>
                 <tr>
                   <!-- 规则描述 -->
                   <td>
                       <el-select v-model="addForm.norm" @change="handleChooseNorm(addForm.norm)" :disabled="disabled2">
                         <el-option v-for="item in monitorNorm" :key="item.index" :label="item.name" :value="item.value"></el-option>
                       </el-select>
                   </td>
                   <!-- 参照类型 -->
                   <td>
                     <el-form-item prop="refrenceType" style="height:24px;"  v-if="isShow2">
                       <el-select v-model="addForm.refrenceType" @change="handleChooseReType(addForm.refrenceType)" :disabled="disabled3"  >
                         <el-option v-for="item in refrence_type" :key="item.index" :label="item.name" :value="item.value"></el-option>
                       </el-select>
                     </el-form-item>
                     <el-form-item prop="refrenceType" style="height:24px;" v-if="!isShow2" >
                        <el-input style="width:85px;" disabled v-model="text"></el-input>
                       </el-form-item>
                   </td>
                   <!-- 运算符 -->
                   <td>
                     <el-form-item prop="comparison" style="height:24px;">
                       <el-select   v-model="addForm.comparison">
                         <el-option  :label="item.name" :value="item.value" v-for="item in comparison" :key="item.index"></el-option>
                        </el-select>
                       </el-form-item>
                   </td>
                   <!-- 阀值 -->
                   <td>
                      <el-form-item prop="threshold" style="height:24px;">
                                    <el-input  placeholder="阀值" v-model="addForm.threshold" type="number" @blur="checkFz(addForm.threshold)"></el-input>
                                </el-form-item>
                   </td>
                   <!-- 单位 -->
                    <td>
                      <el-form-item prop="unitType" style="height:24px;" v-if="isShow" >
                                    <el-select  style="width:80px" placeholder="单位"  v-model="addForm.unitType">
                                        <el-option :value="item.value" :label="item.name" v-for="item in unit_type" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item prop="unitType" style="height:24px;" v-if="!isShow" >
                                    <el-input  v-model="addForm.unitType" style="width:80px"  disabled></el-input>
                                </el-form-item>
                            </td>
                            <!-- 监控频率/分钟 -->
                            <td>
                                <el-form-item prop="frequency" style="height:24px;">
                                    <el-select   v-model="addForm.frequency">
                                        <el-option :label="item.name" :value="item.value" v-for="item in monitor_frequency" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                            <!-- 监控指标	 -->
                            <td>
                                <el-form-item prop="frequencyType" style="height:24px;">
                                    <el-select  v-model="addForm.frequencyType">
                                        <el-option :label="item.name" :value="item.value" v-for="item in frequency_type" :key="item.index"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                            <!-- 出现次数 -->
                            <td>
                                <el-form-item prop="times" style="height:24px;" >
                                    <el-select
                                        v-model="addForm.times"
                                        filterable
                                        allow-create
                                        default-first-option
                                        placeholder="请选择">
                                        <el-option  :label="item.name" 
                                                    :value="item.value" 
                                                    v-for="item in appear_time" 
                                                    :key="item.index"
                                                ></el-option>
                                    </el-select> 
                                </el-form-item>
                            </td>
                            <td>
                                <el-button type="text" size="small"  @click="hanleAddBtn">确认添加</el-button>
                            </td>
                        </tr>
                        <!-- 新增的行 -->
                        <tr v-for="(item,index) in alarmRuleDetails" :key="item.index" v-if="alarmRuleDetails.length != 0">
                            <td>{{item.alarmRuleDetails2}}</td>
                            <td>{{item.refrenceType2}}</td>
                            <td>{{item.comparison}}</td>
                            <td>{{item.threshold}}</td>
                            <td>{{item.unitType}}</td>
                            <td>{{item.frequency}}</td>
                            <td>{{item.norm2}}</td>
                            <td>{{item.times}}</td>
                            <td>
                                <el-button type="text" size="small" @click="handleDelete(index)">删除</el-button>
                            </td>
                 </tr>
               </table>
            </el-form-item>
          <span style="margin-left: 25px;font-size:16px;color: rgb(96, 98, 102);">通知规则</span>
          <el-form-item prop="level" label="告警级别" style="margin:20px 0;">
            <el-select v-model="addForm.level">
              <el-option v-for="item in alarm_level" :key="item.index" :label="item.name + '级'" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="通知对象">
                <el-select size="small"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="输入联系人"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    v-model="addForm.noticeLinkman"
                    @change="handleChoosePeople(addForm.noticeLinkman)"  value-key="linkName">
                    <el-option   v-for="item in lxpeoeleList" 
                                :value="item" 
                                :label="item.linkName"
                                :disabled="item.d"
                                :key="item.index"
                                ></el-option>
                </el-select>
            </el-form-item>

             <el-form-item label="">
                <el-tag closable v-for="(item,index) in choosePeople"  :key="item.index"  @close="handleClose(index,item)" type="info" style="margin-left:4px;font-size:12px;">
                    {{item.linkName}}
                </el-tag>
            </el-form-item>


          <el-form-item label="通知方式">
              <el-checkbox-group  v-model="addForm.noticeType">
                    <el-checkbox label="1" >邮箱</el-checkbox>
                </el-checkbox-group>
          </el-form-item>

          <el-form-item label="通知频率">
              <el-radio-group   v-model="addForm.noticeRate">
                    <el-radio label="1">每次</el-radio>
                    <el-radio label="2">每小时</el-radio>
                    <el-radio label="3">不通知</el-radio>
                </el-radio-group>
          </el-form-item>

          
          <el-form-item style="margin-top:20px;">
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button @click="returnbtn">取消</el-button>
            </el-form-item>
        </el-form>
        </div>
        <!-- 规则 end -->
      </el-scrollbar>
      <!-- 滚动内容 end -->
    </div>
</template>
<script>
import { getDicInfo, saveAlarmRule, pageAlarmContactMan } from "@/service/swagger/AlarmController";
import pageTitle from "@/view/layout/components/content/pageTitle";
export default {
  components: {
    pageTitle,
  },
  data() {
    return {
      //页面主标题
      pageTitle: "创建告警规则",
      monitorNorm: [],//规则描述
      text: "监控比",
      disabled2: false,
      disabled3: false,
      alarm_level: [],
      choosePeople: [],
      isShow: true,
      isShow2: true,
      refrence_type: [],
      unit_type: [],
      copy_monitor_norm: [],
      monitor_norm: [],
      comparison: [],
      monitor_frequency: [],
      frequency_type: [],
      appear_time: [],
      alarm_notify_type: '',
      alarm_notice_rate: '',
      loading: false,
      lxpeoeleList: [],
      alarmRuleDetails: [],//警告规则列表
      addForm: {
        refrenceType: '',//监控值  监控比
        unitType: '',//单位
        name: '',//规则名称 
        alarmRuleDetails: '',//报警规则描述
        comparison: '',//运算发
        threshold: '',//阀
        frequency: '',//出现频率
        frequencyType: '',//出现方式
        norm: '',//描述
        times: '',//次数
        level: '',//警告级别，
        monitorTarget: '',//监控目标，主机IP、容器ID、应用实例编号等
        monitorType: '',//监控资源类型 0：主机 1：容器 2：应用 
        noticeConten: '',//通知内容 
        noticeLinkman: '',//通知人ID 
        noticeRate: '1',//通知频率，不能为空 
        noticeType: ['1'],//通知方式
      },
      rules: {
        refrenceType: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        comparison: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        threshold: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        unitType: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        frequency: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        frequencyType: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        times: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        noticeRate: [
          { required: true, message: '请选择通知频率', trigger: 'blur' }
        ]
      },
    }
  },
  updated() {
    //当添加列表清空的时候
    if (this.alarmRuleDetails.length === 0) {
      this.disabled2 = false
      this.disabled3 = false
    }
  },
  mounted() {
    getDicInfo({}).then(ret => {
      if (ret.code === 0) {
        this.monitorNorm = ret.data.monitor_norm//规则描述
        this.alarm_level = ret.data.alarm_level //告警级别
        this.alarm_notice_rate = ret.data.alarm_notice_rate,//通知频率组
          this.alarm_notify_type = ret.data.alarm_notify_type,//通知方式组
          this.appear_time = ret.data.appear_time,//频率出现次数
          this.comparison = ret.data.comparison,//比较运算符
          this.frequency_type = ret.data.frequency_type,//出现方式
          this.monitor_frequency = ret.data.monitor_frequency,//监控频率
          this.copy_monitor_norm = ret.data.monitor_norm,//规则描述copy
          this.unit_type = ret.data.unit_type//单位
        this.refrence_type = ret.data.refrence_type//参照类型
        this.addForm.frequencyType = ret.data.frequency_type[0].value
      }
    })
    // 联系人
    pageAlarmContactMan({}).then(ret => {
      if (ret.code === 0) {
        ret.data.data.forEach(el => {
          el.d = false
        })
        this.lxpeoeleList = ret.data.data
      }
    })

  },
  methods: {
    // 选容器是去掉规则描述的磁盘使用率
    handleChooseType(val) {
      if (val === '1') {
        let newnorm = this.monitorNorm.filter(el => {
          return el.code != "disk_usage"
        })
        this.monitorNorm = newnorm
      } else {
        this.monitorNorm = this.copy_monitor_norm
      }
    },
    // 检查数字
    checkFz(val) {
      let reg = new RegExp(/^[1-9]\d*(\.\d+)?$/)
      if (!val.match(reg)) {
        this.addForm.threshold = ''
      }
    },
    // 选择cup使用率 默认监控比
    handleChooseNorm(type) {
      if (type === 'cpu_usage') {
        this.disabled3 = true
        this.addForm.refrenceType = '2'
        this.isShow = false
        this.isShow2 = false
        this.addForm.unitType = '%'
      } else {
        this.disabled3 = false
        this.addForm.unitType = ''
        this.isShow = true
        this.isShow2 = true
        this.addForm.refrenceType = '1'
      }
    },
    // 选择监控值 或者监控比单位变化
    handleChooseReType(val) {
      if (val === '1') {
        this.addForm.unitType = ''
        this.isShow = true
      } else if (val === '2') {
        this.isShow = false
        this.addForm.unitType = '%'
      }
    },
    //选择联系人  去重
    handleChoosePeople(val) {
      val.d = true
      this.addForm.noticeLinkman = ''
      this.choosePeople.push(val)
    },
    handleClose(index, item) {
      this.lxpeoeleList.forEach(el => {
        if (el.userId == item.userId) {
          el.d = false
        }
      })
      this.choosePeople.splice(index, 1)
    },
    //添加警告规则
    hanleAddBtn() {
      this.disabled2 = true
      let ruler = {
        name: this.addForm.name,
        norm: this.addForm.norm,
        refrenceType: this.addForm.refrenceType,
        comparison: this.addForm.comparison,
        threshold: this.addForm.threshold,
        frequency: this.addForm.frequency,
        unitType: this.addForm.unitType,
        times: this.addForm.times,
        frequencyType: this.addForm.frequencyType
      }

      if (ruler.norm === 'cpu_usage') {
        ruler.alarmRuleDetails2 = 'cpu使用率'
      } else if (ruler.norm === 'disk_usage') {
        ruler.alarmRuleDetails2 = '磁盘使用率'
      } else if (ruler.norm === 'network_flow') {
        ruler.alarmRuleDetails2 = '网络流量'
      } else if (ruler.norm === 'ram_usage') {
        ruler.alarmRuleDetails2 = '内存使用率'
      }

      if (ruler.refrenceType === '1') {
        ruler.refrenceType2 = '监控值'
      } else if (ruler.refrenceType === '2') {
        ruler.refrenceType2 = '监控比'
      }

      if (ruler.frequencyType === '1') {
        ruler.norm2 = '连续出现'
      } else if (ruler.frequencyType === '2') {
        ruler.norm2 = '共计出现'
      }

      if (this.addForm.norm === 'cpu_usage') {
        this.disabled3 = true
      } else {
        this.disabled3 = false
      }
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.alarmRuleDetails.push(ruler)
          this.addForm.comparison = ''//运算
          this.addForm.threshold = ''//阀
          this.addForm.frequency = ''//出现频率
          this.addForm.times = ''//次数
        } else {
          this.$message.error('规则填写不完整')
        }
      })
    },
    // 删除规则警告
    handleDelete(index) {
      this.alarmRuleDetails.splice(index, 1)
    },
    // 远程搜索联系人
    remoteMethod(query) {
      let params = {
        linkName: query
      }
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          getAlarmContact(params).then(ret => {
            if (ret.code === 0) {
              this.lxpeoeleList = ret.data.data
            }
          })
        }, 200)
      } else {
        this.lxpeoeleList = []
      }
    },
    //创建
    onSubmit() {
      if (this.alarmRuleDetails.length != 0 && this.addForm.name != "") {
        this.alarmRuleDetails.forEach(el => {
          for (var key in el) {
            delete el['alarmRuleDetails2']
            delete el['norm2']
            delete el['refrenceType2']
            delete el['name']
          }
        })
        //联系人id数组
        let noticeLinkman = []
        this.choosePeople.forEach(el => {
          noticeLinkman.push(el.userId)
        })
        let params = {
          alarmRuleDetails: this.alarmRuleDetails,
          monitorTarget: this.addForm.monitorTarget,
          monitorType: this.addForm.monitorType,
          name: this.addForm.name,
          noticeRate: this.addForm.noticeRate,
          noticeType: this.addForm.noticeType,
          noticeLinkman: noticeLinkman,
          level: this.addForm.level,
          noticeConten: this.noticeConten,
          norm: this.addForm.norm
        }
        let finalParams = {}
        if (this.alarmRuleDetails.length == 0) {
          //如果指有一条数据并且没点确认添加
          finalParams.norm = this.addForm.norm
          finalParams.monitorType = this.addForm.monitorType
          finalParams.name = this.addForm.name,
            finalParams.monitorTarget = this.addForm.monitorTarget,
            finalParams.noticeRate = this.addForm.noticeRate,
            finalParams.noticeType = this.addForm.noticeType,
            finalParams.noticeLinkman = noticeLinkman,
            finalParams.level = this.addForm.level,
            finalParams.noticeConten = this.noticeConten
          finalParams.alarmRuleDetails = [{
            comparison: this.addForm.comparison,
            frequency: this.addForm.frequency,
            frequencyType: this.addForm.frequencyType,
            norm: this.addForm.norm,
            refrenceType: this.addForm.refrenceType,
            threshold: this.addForm.threshold,
            times: this.addForm.times,
            unitType: this.addForm.unitType,
          }]
        } else {
          // 点了确认添加多条数据
          finalParams = params
        }
        // console.log(finalParams)
        saveAlarmRule(finalParams).then(ret => {
          if (ret.code === 0) {
            this.$message({
              showClose: true,
              message: '创建成功!',
              type: 'success'
            })
            this.$router.push({
              path: 'gz'
            })
          }
        })
      } else {
        this.$message.error('请确认已添加规则，同时规则名称已填写！')
        return false;
      }


    },
    //取消
    returnbtn() {
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.dialog-table {
  width: 98%;
  text-align: center;
  border: 1px solid #ccc;
}
th {
  text-align: center;
  color: #999;
  background: #f5f6fb;
}
td {
}
tr {
  height: 30px;
}
.el-form .el-form-item__error {
  margin-left: 7% !important;
}
.el-input .el-input__suffix .el-icon-circle-close::before{
   	display:none !important;
}
.el-input .el-input__suffix .el-icon-circle-check::before{
   	display:none !important;
}
.wrap{
  width: 100%; 
  margin-top: 25px
}
</style>
